# @File: log.py
# -*- coding: utf-8 -*-
# __author:"super"
# @time:2025/9/18 19:02

import logging
from logging import handlers
import os
from pathlib import Path

FILENAME = str(Path(__file__).resolve().parent.parent/'logs'/'log')


class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }  # 日志级别关系映射

    def __init__(self, filename=FILENAME, level='debug', when='midnight', backCount=10,
                 fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        if not self.logger.handlers:  # 判断是否已经添加了handler 如果存在直接进行写日志不在重复添加handler
            format_str = logging.Formatter(fmt)  # 设置日志格式
            self.logger.setLevel(self.level_relations.get(level))  # 设置日志级别
            self.sh = logging.StreamHandler()  # 往屏幕上输出
            self.sh.setFormatter(format_str)  # 设置屏幕上显示的格式
            
            # Create logs directory if not exists
            log_dir = os.path.dirname(filename)
            if log_dir and not os.path.exists(log_dir):
                os.makedirs(log_dir, exist_ok=True)
            
            self.th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount,
                                                        encoding='utf-8')  # 往文件里写入#指定间隔时间自动生成文件的处理器
            self.th.setFormatter(format_str)  # 设置文件里写入的格式
            self.logger.addHandler(self.sh)  # 把对象加到logger里
            self.logger.addHandler(self.th)

    def get_logger(self):
        self.logger.removeHandler(self.sh)
        self.logger.removeHandler(self.th)
